package java_option.audio;

import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

import java_option.audio.config.AudioConfig;

public class AudioRecorder extends Thread {

	private Boolean isRunning;

	private TargetDataLine targetDataLine;
	
	private int sampleRate = AudioConfig.sampleRate;
	private boolean isBigEndian = AudioConfig.isBigEndian;
	private int sampleSizeInBits = AudioConfig.sampleSizeInBits;
	private int channels = AudioConfig.channels;
	
	public AudioRecorder() {
//
		AudioFormat audioFormat = new AudioFormat(sampleRate, sampleSizeInBits, channels, AudioConfig.isSigned, isBigEndian);

		int sampleRate = (int) audioFormat.getSampleRate();
		int numChannels = audioFormat.getChannels();

		int audioBufferSize = sampleRate * numChannels;

		DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
		try {
			targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
//
//
//
			targetDataLine.open(audioFormat, audioBufferSize);
		} catch (LineUnavailableException e1) {
			e1.printStackTrace();
		}
	}

	public void onStart() {
		targetDataLine.start(); //
		isRunning = true;
		this.start();//
		synchronized (this) {
			this.notify();
		}
	}

	public void onStop() {
		isRunning = null;
		targetDataLine.stop();
		targetDataLine.close();
	}

//
	public void onPause() {
		targetDataLine.stop();
		this.isRunning = false;
	}

//
	public void onResume() {
		targetDataLine.start();
		this.isRunning = true;
		synchronized (this) {
			this.notify();
		}
	}

	public void run() {
		File wavFile = new File("D:/test/" + System.currentTimeMillis() + ".wav");
		while (true) {
			if (isRunning == null) {
				System.out.println("停止");
				break;
			}
			if (isRunning == false) {
				synchronized (this) {
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			AudioInputStream ais = new AudioInputStream(targetDataLine);
			try {
				System.out.println("准备写入");
//
				AudioSystem.write(ais, AudioFileFormat.Type.WAVE, wavFile);
				System.out.println("已经写入文件 " + wavFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
